import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.fragment.app.Fragment
import com.example.liaofengyun.R

class WordListFragment : Fragment() {

    private lateinit var wordListView: ListView
    private val wordList = mutableListOf<String>()
    private lateinit var adapter: ArrayAdapter<String>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_word_list, container, false)
        setHasOptionsMenu(true)
        wordListView = view.findViewById(R.id.word_list_view)
        adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, wordList)
        wordListView.adapter = adapter
        setupListViewListeners()
        return view
    }

    private fun setupListViewListeners() {
        wordListView.setOnItemLongClickListener { parent, view, position, id ->
            showContextMenuForWord(position)
            true
        }
    }

    private fun showContextMenuForWord(position: Int) {
        activity?.openContextMenu(wordListView)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.word_list_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_delete_word -> {
                val selectedPosition = wordListView.selectedItemPosition
                if (selectedPosition!= -1) {
                    showDeleteConfirmationDialog(selectedPosition)
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showDeleteConfirmationDialog(position: Int) {
        AlertDialog.Builder(requireContext())
            .setTitle("确认删除")
            .setMessage("确定要删除这个单词吗？")
            .setPositiveButton("确定") { dialog, which ->
                wordList.removeAt(position)
                adapter.notifyDataSetChanged()
            }
            .setNegativeButton("取消", null)
            .show()
    }
}